package com.hmdp.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.UUID;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.hmdp.utils.RedisConstants.LOGIN_USER_KEY;

@RestController
public class TestController {


    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    IUserService userService;

    /**
     *
     * 把全部的用户信息按登录用户的信息放到redis，
     * 并且把token全部写入一个.txt文件，用于jmeter测试
     */
    @RequestMapping("/run")
    public void putAllUserInfosToRedis() throws IOException {
        FileWriter fileWriter = new FileWriter("D://tokens.txt");
        List<User> users = userService.list();
        for (User user : users) {
            UserDTO userDTO = new UserDTO();
            BeanUtil.copyProperties(user, userDTO);
            String token = LOGIN_USER_KEY + UUID.randomUUID();
            //将bean转换成map，以按hash的格式存储到redis中
            Map<String, Object> userMap = BeanUtil.beanToMap(userDTO,new HashMap<>(),
                    //UserDTO的Long类型无法存储使用stringRedisTemplate存储，需要转换。BeanUtil提供了可供自定义转换的选项
                    CopyOptions.create().setFieldValueEditor((fieldName, fieldValue)->{
                        //其他类型转换成String类型
                        return fieldValue.toString();
                    }));
            fileWriter.write(token + "\n");
            stringRedisTemplate.opsForHash().putAll(token, userMap);
        }

        return;
    }
}
